#!/usr/bin/env python
# -*- coding: utf-8 -*-
#code:utf-8
#
# Copyright(C) 2011 SupDo.com
# Licensed under the GUN License, Version 3.0 (the "License");
# 
# File:        productView.py
# Author:      KuKei
# Create Date: 2012-3-20
# Description: 产品管理视图
# Modify Date: 2012-3-20

from sd.cms.views import BaseView
from sd.cms.lib.decorator import powerLevel, cachePage
from sd.cms.lib import Params, Pager, Result
from sd.cms.forms.appForm import ProductForm, ProductParamForm, ProductCmtForm
from sd.cms.models.paramModel import Catalog
from sd.cms.models.appModel import Product, ProductParam, ProductCmt
import datetime, cgi
from django.db import transaction

class ProductView(BaseView):
    @powerLevel(Params.ADMINISTRATOR)
    def edit(self, **args):
        productForm = ProductForm()
        if self.request.POST:
            productForm = ProductForm(self)
            if productForm.is_valid():
                productData = productForm.cleaned_data
                productData['author'] = self.power['user'].id
                productData['crtdate'] = datetime.datetime.now()
                productData['readcnt'] = 0
                productModel = Product().initData(productData)
                productModel.catalog = productData['catalog']
                productModel.id = int(self.request.POST['_id']) if int(self.request.POST['_id']) >0 else None
                productModel
                productModel.save()
                self.mc.flushNS2(self.params.PRODUCT)
                self.mc.flushNS2(self.params.PRODUCTLIST)
                return self.redirect('product-'+str(productModel.id)+'.html')
            else:
                self.result.msg = productForm.GetErrors()
        productParamForm = ProductParamForm()
        self.viewData['productParamForm'] = productParamForm
        self.viewData['productForm'] = productForm
        return self.render('/addProduct.html')
    
    def delete(self, **args):
        if self.request.POST:
            #有外键关联的数据也会被删除
            Product.objects.get(id=int(args['id'])).delete()
            self.mc.flushPage(Params.PRODUCT, args['id'])
            self.mc.flushNS2(self.params.PRODUCT)
            self.mc.flushNS2(self.params.PRODUCTLIST)
            if self.request.POST.has_key('_retType') and self.request.POST['_retType'] == 'json':
                self.result.flag = True
                self.result.msg = "删除成功！"
                return self.render_json()
            else:
                return self.render('/listProduct.html')
    
    @powerLevel(Params.ADMINISTRATOR)
    def addParam(self, **args):
        try:
            productParamForm = ProductParamForm()
            if self.request.POST:
                if int(self.request.POST['product_id']) <= 0 :
                    self.result = Result(False,'请先添加产品，然后再添加参数！','','',2)
                    return self.render_json()
                productParamForm = ProductParamForm(self)
                if productParamForm.is_valid():
                    paramData = productParamForm.cleaned_data
                    paramModel = ProductParam().initData(paramData)
                    paramModel.product_id = self.request.POST['product_id']
                    paramModel.save()
                    self.mc.flushNS2(self.params.PRODUCT)
                    self.result = Result(True,'操作成功！','','/admin/list!Catalog.html',2)
        except Exception,ex:
            self.result = Result(False,str(ex.args),'','',2)
        return self.render_json()
    
    @powerLevel(Params.ADMINISTRATOR)
    def editParam(self, **args):
        try:
            productParamForm = ProductParamForm()
            if self.request.POST:
                productParamForm = ProductParamForm(self)
                if productParamForm.is_valid():
                    paramData = productParamForm.cleaned_data
                    objId = int(self.request.POST['_id'])
                    if objId > -1:
                        paramModel = ProductParam().initData(paramData)
                        paramModel.product_id = self.request.POST['product_id']
                        paramModel.id = objId
                        paramModel.save()
                        self.result = Result(True,'操作成功！','','',2)
                    else:
                        self.result = Result(False,'此次是新增操作不是编辑操作！','','',2)
                else:
                    self.result = Result(False,productParamForm.GetErrors(),'','',3)
        except Exception,ex:
            self.result = Result(False,str(ex.args),'','',2)
        return self.render_json()
    
    @powerLevel(Params.ADMINISTRATOR)
    def delParam(self, **args):
        try:
            if self.request.POST:
                paramModel = ProductParam.objects.get(id=int(args['id'])).delete()
                #paramModel.delete()
                self.result.flag = True
                self.result.msg = "删除成功！"
        except Exception,ex:
            self.result.flag = False
            self.result.msg = str(ex)
        if self.request.POST.has_key('_retType') and self.request.POST['_retType'] == 'json':
            return self.render_json()
        else:
            return self.redirect('/addProduct.html')
        
    def addCmt(self, **args):
        commentForm = ProductCmtForm()
        if self.request.POST:
            commentForm = ProductCmtForm(self)
            if commentForm.is_valid():
                commentData = commentForm.cleaned_data
                objId = args['id'] if args.has_key('id') and args['id'] else -1
                if int(objId) > -1:
                    commentData['date'] = datetime.datetime.now()
                    commentData['article_id'] = objId
                    commentModel = ProductCmt().initData(commentData)
                    commentModel.save()
                    self.mc.flushPage(Params.ARTICLE, objId)
                    if self.params.SAFECODE in self.request.session:
                        self.request.session.pop(self.params.SAFECODE)
                    self.result.flag = True
                    self.result.msg = '发布成功！'
                    self.viewData = {'id':commentModel.id, 'class':'reply' if commentModel.pid>-1 else '', 'author':commentModel.author, 'theme':self.params.DEFAULTTHEME, 'homepage':commentModel.homepage, 'date':commentModel.date.strftime('%Y-%m-%d %H:%M:%S'), 'content':cgi.escape(commentModel.content)}
                    renderHtml = self.render('/snippet/comment.html')
                    self.result.html = renderHtml._container[0]
                else:
                    self.result.flag = False
                    self.result.msg = '文章ID未可知！'
            else:
                self.result.flag = False
                self.result.msg = commentForm.GetErrors()
        return self.render_json()
    
    @powerLevel(Params.ADMINISTRATOR)
    def delCmt(self, **args):
        if self.request.POST:
            productCmtModel = ProductCmt.objects.get(id=int(args['id']))
            productCmtModel.delete()
            self.mc.flushPage(Params.PRODUCT, productCmtModel.product_id)
            self.result.flag = True
            self.result.msg = "删除成功！"
        else:
            self.result.flag = False
            self.result.msg = "删除失败！"
        return self.render_json()
    
    @powerLevel(Params.ADMINISTRATOR)
    def addView(self, **args):
        productForm = ProductForm()
        productForm.initOptions('catalog', Catalog.objects.toOptionsByModel('Product', 20, ('', '请选择')))
        productParamForm = ProductParamForm()
        self.viewData['productForm'] = productForm
        self.viewData['productParamForm'] = productParamForm
        return self.render('/addProduct.html')
    
    @powerLevel(Params.ADMINISTRATOR)
    def editView(self, **args):
        product = Product.objects.get(id=int(args['id']))
        paramList = list(product.productparam_set.all().order_by('orderby'))
        productForm = ProductForm(self, modelData=product)
        productForm.initOptions('catalog', Catalog.objects.toOptionsByModel('Product', 20, ('', '请选择')))
        self.viewData['productForm'] = productForm
        self.viewData['paramList'] = paramList
        productParamForm = ProductParamForm()
        self.viewData['productParamForm'] = productParamForm
        return self.render('/addProduct.html')
    
    def listView(self, **args):
        productList = None
        catalog = None
        pager = Pager(self.request, 'prd')
        if args.has_key('field') and args['field']:
            catalog = self.getCatalog()[1][args['field']]
            pager.totalSize = Product.objects.filter(catalog=catalog, status__in=[1,2]).count()
            productList = list(Product.objects.filter(catalog=catalog, status__in=[1,2]).order_by('crtdate')[pager.startSize:pager.getEndSize()])
        else:
            pager.totalSize = Product.objects.filter(status__in=[1,2]).count()
            productList = list(Product.objects.filter(status__in=[1,2]).order_by('crtdate')[pager.startSize:pager.getEndSize()])
        self.viewData['productList'] = productList
        self.viewData['pager'] = pager.getPageList()
        self.viewData['lctList'] = self.getLocationLists(catalog)
        return self.render('/listProduct.html')
    
    @powerLevel(Params.ADMINISTRATOR)
    def listAllView(self, **args):
        pager = Pager(self.request, 'prd')
        pager.totalSize = Product.objects.all().order_by('-crtdate').count()
        productList = list(Product.objects.all().order_by('-crtdate')[pager.startSize:pager.getEndSize()])
        catalogDict = self.getCatalog()[2]
        for i in range(0, len(productList)):
            productList[i].catalog = catalogDict[productList[i].catalog_id]
        self.viewData['productList'] = productList
        self.viewData['pager'] = pager.getPageList()
        return self.render('/admin/listAllProduct.html')
    
    def view(self, **args):
        product = None
        if args.has_key('id') and args['id']:
            product = Product.objects.get(id=int(args['id']))
        else:
            product = Product.objects.get(name=args['name'])
        paramList = list(product.productparam_set.filter(isdisplay=True).order_by('orderby'))
        product.readcnt = product.readcnt+1
        product.save()
        pager = Pager(self.request, 'cmt')
        pager.totalSize = product.productcmt_set.all().count()
        cmtList = list(product.productcmt_set.filter(pid=-1).order_by('date')[pager.startSize:pager.getEndSize()])
        idList = [cmt.id for cmt in cmtList]
        cmtList2 = list(product.productcmt_set.filter(pid__in=idList).order_by('date'))
        self.viewData['cmtList'] = cmtList
        self.viewData['cmtList2'] = cmtList2
        self.viewData['cmtForm'] = ProductCmtForm()
        self.viewData['pager'] = pager.getPageList()
        self.viewData['product'] = product
        self.viewData['paramList'] = paramList
        self.viewData['lctList'] = self.getLocationLists(product.catalog, product.title)
        return self.render('/product.html')
    
    def detailView(self, **args):
        paramModel = ProductParam.objects.get(id=int(args['id']))
        paramForm = ProductParamForm(self,modelData=paramModel)
        #catalogForm.clearErrors()
        self.viewData["etype"] = 'detail'
        self.viewData["e"] = paramForm
        return self.render('/admin/snippet/detail.html')
    
def action(request, **args):
    return apply(ProductView(request).action, (), args)